<?php
/**
 * Created by User: wene<china_wangyu@aliyun.com> Date: 2019/3/4 Time: 14:43
 */

namespace think\restful\exception;

use Exception;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\ValidateException;
use think\restful\response\Json;
use Throwable;

/**
 * Class ApiException API接口异常 捕获/输出 类
 * @package think\restful\exception
 */
class ApiException extends Handle
{

    public static function exception($message = '操作失败~', $code = 400)
    {
        // 抛出 HTTP 异常
        Json::response($code,$message);
    }

    public function render(Exception $e)
    {
        // 参数验证错误
        if ($e instanceof ValidateException) {
            Json::response(422,$e->getError());
        }
        // 请求异常
        if ($e instanceof HttpException && request()->isAjax()) {
            Json::response($e->getStatusCode(),$e->getMessage());
        }
        // 其他错误交给系统处理
        return parent::render($e); // TODO: Change the autogenerated stub
    }

}